﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using Entities = GMAC.ReportingSystem.Business.Entities;
using System.Data;
using Components = GMAC.ReportingSystem.Business.Components;
using FrameworkManapro.Utilities;

namespace GMAC.ReportingSystem.Paginas
{
    public partial class Checks : System.Web.UI.Page
    {
        #region Page Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated || Session["User"] == null)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            if (IsPostBack) return;
            Initialize();
            ValidateSecurity();
            
        }

        #endregion

        #region Button Events

        protected void btnNew_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                var frc = new Components.CheckComponent();
                var Check = ReadCheck();
                Check.ID = frc.Create(Check);
                var audit = new FrameworkManapro.Audit.Audit<Entities.Check>
                {
                    EntityKey = Check.ID.ToString(),
                    EventDate = DateTime.Now,
                    EventType = FrameworkManapro.Audit.AuditEvent.Insert,
                    NewObject = Check,
                    UserId = ((Entities.User)Session["User"]).UserID
                };
                var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.Check>(audit);
                auditDAC.InsertAudit();
                wucMessage.ShowMessage(UserControls.MessageType.Success, "The Check was successfully saved.", null);
                popupExtenderMessage.Show();
                this.PagingControl.TotalRecords = Search();
                Search();

                ClearFields();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "New Check", "btnNew_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Check could not be saved", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnSave_Click(object sender, ImageClickEventArgs e)
        {
         btnSave.Visible = false;
            btnNew.Visible = true;
            var frc = new  Components.CheckComponent();
            try
            {
                var Check = ReadCheck();
                if (hfID.Value.Trim() != string.Empty)
                {
                    Check.ID = int.Parse(hfID.Value);
                    var oldCheck = frc.GetDetails(Check.ID);
                    frc.Edit(Check);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.Check>
                    {
                        EntityKey = Check.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Update,
                        OldObject = oldCheck,
                        NewObject = Check,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.Check>(audit);
                    auditDAC.InsertAudit();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The Check was successfully saved.", null);
                    popupExtenderMessage.Show();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    ClearFields();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Save Check", "btnSave_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Check couldn't be saved.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnCancel_Click(object sender, ImageClickEventArgs e)
        {
            btnSave.Visible = false;
            btnNew.Visible = true;
            ClearFields();
        }
        protected void btnModify_Click(object sender, ImageClickEventArgs e)
        {
          if (grvchecks != null)
            {
                if (grvchecks.SelectedDataKey != null)
                {
                    try
                    {
                        var CheckId = (int)this.grvchecks.SelectedDataKey.Value;
                        var frc = new Components.CheckComponent();
                        var Check = frc.GetDetails(CheckId);
                        hfID.Value = CheckId.ToString();
                        txtCheckNumber.Text = Check.CheckNumber;
                        txtAmount.Text = Check.Amount.ToString("N2");
                        ddlBank.SelectedValue = Check.Bank.DebitBankCode.ToString();
                        txtDate.Text = Check.dDate.ToString("dd/MM/yyyy");
                        btnSave.Visible = true;
                        btnNew.Visible = false;
                    }
                    catch (Exception ex)
                    {
                        FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Modify Check", "btnModify_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                        wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred changing the Check.", ex.ToString());
                        popupExtenderMessage.Show();
                    }
                }
                else
                {
                    wucMessage.ShowMessage(UserControls.MessageType.Information, "A Check must be selected.", null);
                    popupExtenderMessage.Show();
                }
            }
        }
        protected void btnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (grvchecks.SelectedDataKey != null)
            {
                popupExtenderConfirm.Show();
            }
            else
            {
                wucMessage.ShowMessage(UserControls.MessageType.Information, "A Check must be selected.", null);
                popupExtenderMessage.Show();
            }
        }
        protected void btnConfirm_Click(object sender, ImageClickEventArgs e)
        {
             try
            {
                var frc = new Components.CheckComponent();
                if (grvchecks.SelectedDataKey != null)
                {
                    var CheckId = (int)this.grvchecks.SelectedDataKey.Value;
                    var Check = new Entities.Check { ID = CheckId };
                    var oldCheck = frc.GetDetails(Check.ID);
                    frc.Delete(Check);
                    var audit = new FrameworkManapro.Audit.Audit<Entities.Check>
                    {
                        EntityKey = Check.ID.ToString(),
                        EventDate = DateTime.Now,
                        EventType = FrameworkManapro.Audit.AuditEvent.Delete,
                        OldObject = oldCheck,
                        UserId = ((Entities.User)Session["User"]).UserID
                    };
                    var auditDAC = new FrameworkManapro.Audit.AuditDataAccess<Entities.Check>(audit);
                    auditDAC.InsertAudit();
                    this.PagingControl.TotalRecords = Search();
                    Search();
                    wucMessage.ShowMessage(UserControls.MessageType.Success, "The Check was successfully deleted.", null);
                    popupExtenderMessage.Show();
                }
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Delete Check", "btnConfirm_Click", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "The Check couldn't be deleted.", ex.ToString());
                popupExtenderMessage.Show();
            }
            
        }
        protected void imgBuscarReg_Click(object sender, ImageClickEventArgs e)
        {
            this.PagingControl.TotalRecords = Search();
            Search();
            if (this.PagingControl.TotalRecords == 0)
            {
                PagingControl.Visible = false;
            }
            else
            {
                PagingControl.Visible = true;
            } 
            ClearFields();
        }
        
        #endregion

        #region Other Events

        protected void grvchecks_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(grvchecks, "Select$" + e.Row.RowIndex);

                //if (!string.IsNullOrEmpty((e.Row.FindControl("hfBankId") as HiddenField).Value))
                //{
                //    var hfBankId = int.Parse((e.Row.FindControl("hfBankId") as HiddenField).Value);
                //    var bc = new Components.BankComponent();
                //    var Bank = bc.GetDetails(hfBankId);
                //    e.Row.Cells[3].Text = Bank.DebitBankName;
                //}
            }
            
           
        }

        #endregion

        #region Private Methods

        private void ClearFields()
        {
            hfID.Value = string.Empty;
            txtCheckNumber.Text = string.Empty;
            txtAmount.Text = string.Empty;
            ddlBank.SelectedValue = string.Empty;
            txtDate.Text = string.Empty;

        }
        private void Initialize()
        {
            try
            {

                var bcBank             = new Components.BankComponent();
                ddlBank.DataSource     = bcBank.GetList();
                ddlBank.DataTextField  = "DebitBankName";
                ddlBank.DataValueField = "DebitBankCode";

                ddlBank.DataBind();
                ddlBank.Items.Insert(0, new ListItem("Select...", string.Empty));

                ddlBankSearch.DataSource     = bcBank.GetList();
                ddlBankSearch.DataTextField  = "DebitBankName";
                ddlBankSearch.DataValueField = "DebitBankCode";
                ddlBankSearch.DataBind();
                ddlBankSearch.Items.Insert(0, new ListItem("All...", string.Empty)); 

            
                
                btnSave.Visible = false;
                btnNew.Visible = true;
                wucMessageConfirm.ShowMessage(UserControls.MessageType.Information,
                                              "Are you sure you want to delete the selected check?", null);
                this.PagingControl.TotalRecords = Search();
                Search();
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Initialize page", "Initialize", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error occurred initializing the page.", ex.ToString());
                popupExtenderMessage.Show();
            }
            
        }
        private void ValidateSecurity()
        {
            var beEntities = ((Entities.User)Session["User"]).Role.Security.GetEntitySecurity("Checks");
            if (beEntities == null) return;
            if (!beEntities.CanRead)
            {
                grvchecks.Visible = false;
                btnModify.Visible = false;
                btnDelete.Visible = false;
                pnlSearch.Visible = false;
            }
            if (!beEntities.CanWrite)
            {
                btnSave.Visible = false;
            }
            if (!beEntities.CanInsert)
            {
                btnNew.Visible = false;
                btnCancel.Visible = false;
                pnlEdit.Visible = false;
            }
            if (!beEntities.CanDelete)
            {
                btnDelete.Visible = false;
            }
        }
        private int Search()
        {
            try
            {
                var bc = new  Components.CheckComponent();
                DateTime? DateSearch = null;
                if (!string.IsNullOrEmpty(txtDateSearch.Text))
                    DateSearch = DateTime.Parse(txtDateSearch.Text);
                string CheckNumber = txtCheckNumberSearch.Text;
                int? BankId = null;
                if (!string.IsNullOrEmpty(ddlBankSearch.SelectedValue))
                    BankId = int.Parse(ddlBankSearch.SelectedValue);

                FrameworkManapro.WebUI.PagingDetails paging = new FrameworkManapro.WebUI.PagingDetails();
                paging.PageNumber = this.PagingControl.PageNumber;
                paging.PageSize = this.PagingControl.PageSize;
                paging.SortBy = this.PagingControl.SortExpression;
                paging.SortDirection = this.PagingControl.SortDirection;



                Entities.CheckCollection Checkcollection = bc.Search(CheckNumber, DateSearch, BankId, paging);

                grvchecks.DataSource = Checkcollection;
                grvchecks.DataBind();
                return Checkcollection.TotalResults;
            }
            catch (Exception ex)
            {
                FrameworkManapro.ErrorHandling.LoggingError.PostErrorEventViewer(ex.Message, "Search Check", "void Search", System.Diagnostics.TraceEventType.Error, ex.StackTrace);
                wucMessage.ShowMessage(UserControls.MessageType.Error, "An error has occurred during the search.", ex.ToString());
                popupExtenderMessage.Show();
                return  0;

            }
        }
        private Entities.Check ReadCheck()
        {
            var Check = new  Entities.Check
            {
                CheckNumber = txtCheckNumber.Text,
                dDate = DateTime.Parse(txtDate.Text),
                Amount = Decimal.Parse(txtAmount.Text),
           };
            Check.Bank = new GMAC.ReportingSystem.Business.Entities.Bank();
            Check.Bank.DebitBankCode = int.Parse(ddlBank.SelectedValue);
            if (!string.IsNullOrEmpty(hfID.Value))
            {
                Check.ID = int.Parse(hfID.Value);
            }   
            return Check;
        }
        protected void pagingControl_PageChanged(object sender, EventArgs e)
        {
             Search();
        }
        #endregion

 

    }
}
